package com.ujs.code.Matrix;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * LCR 146. 螺旋遍历二维数组
 *
 * @author zhangshihao
 * @create 2023-09-26 14:53
 */
public class SpiralArray {
    public static void main(String[] args) {
        SpiralArray spiralArray = new SpiralArray();
        int[][] matrix = {
                {2, 3}
        };
        int[] ints = spiralArray.spiralArray(matrix);
        System.out.println(Arrays.toString(ints));
    }

    public int[] spiralArray(int[][] array) {
        if (array.length == 0) {
            return new int[0];
        }
        int n = array.length;
        int m = array[0].length;
        int l = Math.max(array.length, array[0].length);
        int[] ints = new int[n * m];
        int count = 0;
        int i, j;  // i代表行，j代表列
        int loop = 0;
        int start = 0;
        while (loop++ < l) {
            for (j = start; j < m - loop; j++) {
                ints[count++] = array[start][j];
                if (count == n * m) {
                    return ints;
                }
            }
            for (i = start; i < n - loop; i++) {
                ints[count++] = array[i][j];
                if (count == n * m) {
                    return ints;
                }
            }
            for (; j >= loop; j--) {
                ints[count++] = array[i][j];
                if (count == n * m) {
                    return ints;
                }
            }
            for (; i >= loop; i--) {
                ints[count++] = array[i][j];
                if (count == n * m) {
                    return ints;
                }
            }
            start++;
        }
        if (n == 1 && m == 1) {
            ints[0] = array[0][0];
            return ints;
        }
        if (l % 2 == 1) {
            // 添加中间位置的数字
            ints[n * m - 1] = array[n / 2][n / 2];
        }
        return ints;
    }
}
